<?php

// phpinfo();


require_once 'mp3\Smarty.php';
require_once 'mp3\Constants.php';

$smarty = new mp3_Smarty();

require_once 'mp3\musicBrainz.php';
require_once 'mp3\InfoArtista.php';
require_once 'mp3\InfoCanco.php';
require_once 'mp3\Getid3.php';

require 'mp3/ComprovarSessio.php';

if(isset($_POST['inici'])){
		echo $smarty->fetch('mp3\header.tpl');
		echo $smarty->fetch('mp3\pujarCanco.tpl');
		echo $smarty->fetch('mp3\footer.tpl');
}
else if (isset($_FILES['fitxer'])) {
	$nom = htmlentities($_FILES["fitxer"]["name"]);
	$_SESSION['arxiu']=sha1(Mp3_Constants::SALT.$nom);
	$getID3 = new Mp3_GetID3();
	$ThisFileInfo = $getID3->analyze($_FILES["fitxer"]["tmp_name"]);
	$artistes = $ThisFileInfo['id3v2']['comments']['artist'][0];
	$titol = $ThisFileInfo['id3v2']['comments']['title'][0];
	if ($artistes == ''){
		$artistes = $ThisFileInfo['id3v1']['comments']['artist'][0];
	}
	if ($titol == ''){
		$titol = $ThisFileInfo['id3v1']['comments']['artist'][0];
	}
	$a = move_uploaded_file($_FILES["fitxer"]["tmp_name"], Mp3_Constants::PATH_CANCONS.$nom);
	$smarty->assign('arxiu', $nom);
	$smarty->assign('artistes', $artistes);
	$smarty->assign('titol', $titol);
	echo $smarty->fetch('mp3\header.tpl');
	echo $smarty->fetch('mp3\pujarCanco.tpl');
	echo $smarty->fetch('mp3\footer.tpl');
}

if (array_key_exists('musicBrainz', $_POST)){
	$resposta = Mp3_MusicBrainz::getInfoCanco($_POST['titol'], $_POST['artista']);
	$artistes = array();
	$count = $resposta->children()->attributes();
	$canco = new Mp3_InfoCanco();
	if ($count['count'] != 0){
		$child = $resposta->children()->children()->children();
		$canco->llegir($child);
	}
	if ($canco->artista == ''){
		$canco->artista = $_POST['artista'];
	}
	if ($canco->titol == ''){
		$canco->titol = $_POST['titol'];
	}
	$smarty->assign('arxiu', $_POST['arxiu']);
	$smarty->assign('canco', $canco);
	echo $smarty->fetch('mp3\header.tpl');
	echo $smarty->fetch('mp3\formulari.tpl');
	echo $smarty->fetch('mp3\footer.tpl');
}
if (array_key_exists('guardar', $_POST)){
	$canco = new Mp3_InfoCanco();
	if ($canco->artista == ''){
		$canco->artista = $_POST['artista'];
	}
	if ($canco->titol == ''){
		$canco->titol = $_POST['titol'];
	}
	$smarty->assign('arxiu', $_POST['arxiu']);
	$smarty->assign('canco', $canco);
	echo $smarty->fetch('mp3\header.tpl');
	echo $smarty->fetch('mp3\formulari.tpl');
	echo $smarty->fetch('mp3\footer.tpl');	
}

